import { Injectable } from '@nestjs/common';
import { InjectEntityManager } from '@nestjs/typeorm';
import { generateRandomStr } from '../utils';
import { EntityManager } from 'typeorm';
import { UniqueCode } from './entities/UniqueCode';
import { Cron, CronExpression } from '@nestjs/schedule';
import { ShortLongMap } from './entities/ShortLongMap';

@Injectable()
export class UniqueCodeService {

    @InjectEntityManager()
    private entityManager: EntityManager

    // @Cron(CronExpression.EVERY_5_SECONDS)
    async generateCode() {
        let str = generateRandomStr(6)
        const uniqueCode = await this.entityManager.findOneBy(UniqueCode, {
            code: str
        })
        if (!uniqueCode) {
            const code = new UniqueCode()
            code.code = str
            code.status = 0
            return await this.entityManager.insert(UniqueCode, code)
        } else {
            return this.generateCode()
        }
    }

    @Cron(CronExpression.EVERY_DAY_AT_4AM)
    async batchGenerateCode() {
        for (let i = 0; i < 10000; i++) {
            this.generateCode()            
        }
    }

    async generate(longUrl: string) {
        let uniqueCode = await this.entityManager.findOneBy(UniqueCode, {
            status: 0
        })
        if (!uniqueCode) {
            uniqueCode = await this.generateCode()
        }
        const map = new ShortLongMap()
        map.shortUrl = uniqueCode.code
        map.longUrl = longUrl

        await this.entityManager.insert(ShortLongMap, map)
        await this.entityManager.update(UniqueCode, {
            id: uniqueCode.id
        }, {
            status: 1
        })
        return uniqueCode.code
    }  

    async getLongUrl(code: string) {
        const map = await this.entityManager.findOneBy(ShortLongMap, {
            shortUrl: code
        })
        if (!map) {
            return null
        }
        return map.longUrl
    }
}
